﻿using LPBToolsLib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using 电子票存档工具;

namespace EBillSer_V1
{
    public partial class UploadEBill : System.Web.UI.Page
    {
        public Dictionary<string, object> tRecReqDatas { get; private set; }
        public Dictionary<string, object> ResponseValues { get; private set; }
        MySQLConfigDict DBServerCFG { get; }
        protected void Page_Load(object sender, EventArgs e)
        {
            bool isDebug = true;

            Dictionary<string, object> MySQLDBInfo = new Dictionary<string, object>();
            MySQLDBInfo.Add("Address", "127.0.0.1");
            MySQLDBInfo.Add("DBUser", "AppDBUser");
            MySQLDBInfo.Add("DBPass", "DBX2024");
            MySQLDBInfo.Add("DBName", "AppUserSer");
            MySQLDBInfo.Add("DBPort", "3306");

            string SysToken = WebConfigurationManager.AppSettings["SysToken"];
            string DBType = WebConfigurationManager.AppSettings["DBType"];

            if (string.IsNullOrEmpty(SysToken))
                SysToken = Guid.NewGuid().ToString().Replace("-", string.Empty).ToUpper();

            string sRespon = "";
            tRecReqDatas = null;
            JavaScriptSerializer tSerializer = new JavaScriptSerializer();
            // 初始化用请求应答
            ResponseValues = new Dictionary<string, object>();
            ResponseValues.Add("err", 0);
            ResponseValues.Add("msg", "ready");
            ResponseValues.Add("reqtype", "get");
            if (isDebug)
            {
                ResponseValues.Add("SysToken", SysToken);
            }

            Response.Clear();
            Response.ContentType = "application/json";
            Response.Charset = "utf-8";
            try
            {
                // POST类型请求，提取Post数据
                Stream sRecDataStream = Request.InputStream;
                if (sRecDataStream.Length > 0)
                {
                    ResponseValues["type"] = "post";
                    byte[] tRecBuf = new byte[sRecDataStream.Length];
                    sRecDataStream.Read(tRecBuf, 0, (int)sRecDataStream.Length);
                    try
                    {
                        string sTmp = Encoding.UTF8.GetString(tRecBuf);
                        tRecReqDatas = (Dictionary<string, object>)tSerializer.DeserializeObject(sTmp);
                        ResponseValues.Add("pdata", tRecReqDatas);
                    }
                    catch (Exception ex)
                    {
                    }
                }
                ResponseValues.Add("url", Request.Url.ToString());
                string sAPIName = Request.QueryString["api"];
                if (!string.IsNullOrEmpty(sAPIName))
                {
                    ResponseValues.Add("api", sAPIName);

                    if (tRecReqDatas == null)
                        tRecReqDatas = new Dictionary<string, object>();

                    // 将Query参数也放入tRecPostDatas中
                    string[] tQKeys = Request.QueryString.AllKeys;
                    foreach (string key in tQKeys)
                        if (!tRecReqDatas.ContainsKey(key))
                            tRecReqDatas.Add(key, Request.QueryString[key]);
                    //ResponseValues.Add("gdata", tRecReqDatas);
                }
                string sErrMsg = "";
                int iErrCode = 0;

                Dictionary<string, object> tResult = new Dictionary<string, object>();

                MySQLConfigDict tMySqlCFG = new MySQLConfigDict(MySQLDBInfo);

                if ((tRecReqDatas != null)
                    && tRecReqDatas.ContainsKey("token")
                    && (!string.IsNullOrEmpty(tRecReqDatas["token"].ToString()))
                    && tRecReqDatas.ContainsKey("ebillxml")
                    && (!string.IsNullOrEmpty(tRecReqDatas["ebillxml"].ToString())))
                {

                }



                    if ((iErrCode >= 0) && (tResult != null) && (tResult.Count > 0))
                {
                    if (ResponseValues.ContainsKey("result"))
                        ResponseValues["result"] = tResult;
                    else
                        ResponseValues.Add("result", tResult);
                }
                ResponseValues["err"] = iErrCode;
                ResponseValues["msg"] = sErrMsg;

                // 应答
                sRespon = tSerializer.Serialize(ResponseValues);
            }
            catch
            {
                sRespon = "";
            }
            finally
            {
                if (!string.IsNullOrEmpty(sRespon))
                {
                    Response.Write(sRespon);
                    Response.Flush();
                }
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
        }

        public bool saveXMLtoDB(string sXMLStr, out string EIid)
        {
            bool iResult = false;
            EIid = "";
            if (!string.IsNullOrEmpty(sXMLStr))
                try
                {
                    // 加载XML文档
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(sXMLStr);

                    // 提取票据编号
                    XmlNodeList booksEIid = xmlDoc.GetElementsByTagName("EIid");
                    if (booksEIid.Count > 0)
                    {
                        EIid = booksEIid[0].InnerText.Trim();

                        if ((EBillsMySqlTools.createEBill(DBServerCFG, EIid))
                            && (EBillsMySqlTools.updateEBillBlob(DBServerCFG, EIid, "ElecBill", sXMLStr)))
                        {
                            iResult = true;

                            // 获取所有的"book"元素
                            XmlNodeList booksHeader = xmlDoc.GetElementsByTagName("Header");
                            foreach (XmlNode book in booksHeader)
                            {
                                XmlNodeList bookData = book.ChildNodes;
                                foreach (XmlNode data in bookData)
                                {
                                    switch (data.Name)
                                    {
                                        case "EIid":
                                            Console.WriteLine($"票据号: {data.InnerText.Trim()}");
                                            break;
                                        case "Version":
                                            Console.WriteLine($"版本: {data.InnerText.Trim()}");
                                            break;
                                        case "EInvoiceTag":
                                            Console.WriteLine($"类型: {data.InnerText.Trim()}");
                                            break;
                                    }
                                }
                            }
                            XmlNodeList booksInherentLabel = xmlDoc.GetElementsByTagName("InherentLabel");
                            foreach (XmlNode book in booksInherentLabel)
                            {
                                XmlNodeList bookData = book.ChildNodes;
                                foreach (XmlNode data in bookData)
                                {
                                    switch (data.Name)
                                    {
                                        case "InIssuType":
                                            Console.WriteLine($"{data.ChildNodes[1].InnerText.Trim()}: {data.ChildNodes[0].InnerText.Trim()}");

                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "InIssuType", data.ChildNodes[0].InnerText.Trim().Equals("Y") ? "1" : "0");
                                            break;
                                        case "EInvoiceType":
                                            Console.WriteLine($"{data.ChildNodes[1].InnerText.Trim()}: {data.ChildNodes[0].InnerText.Trim()}");
                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "EInvoiceType", data.ChildNodes[0].InnerText.Trim());
                                            break;
                                        case "GeneralOrSpecialVAT":
                                            Console.WriteLine($"{data.ChildNodes[1].InnerText.Trim()}: {data.ChildNodes[0].InnerText.Trim()}");
                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "GeneralOrSpecialVAT", data.ChildNodes[0].InnerText.Trim());
                                            break;
                                        case "TaxpayerType":
                                            Console.WriteLine($"{data.ChildNodes[1].InnerText.Trim()}: {data.ChildNodes[0].InnerText.Trim()}");
                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "TaxpayerType", data.ChildNodes[0].InnerText.Trim());
                                            break;
                                    }
                                }
                            }
                            // 红字票专有信息
                            XmlNodeList booksRedEInvoice = xmlDoc.GetElementsByTagName("RedEInvoice");
                            foreach (XmlNode book in booksRedEInvoice)
                            {
                                XmlNodeList bookData = book.ChildNodes;
                                foreach (XmlNode data in bookData)
                                {
                                    switch (data.Name)
                                    {
                                        case "OriginalInvoiceCode":
                                            Console.WriteLine($"被红冲蓝字数电票号码: {data.ChildNodes[0].InnerText.Trim()}");
                                            break;
                                        case "CreditNoteNumber":
                                            Console.WriteLine($" 红字发票信息确认单编号: {data.ChildNodes[0].InnerText.Trim()}");
                                            break;
                                    }
                                }
                            }

                            XmlNodeList booksSellerInformation = xmlDoc.GetElementsByTagName("SellerInformation");
                            foreach (XmlNode book in booksSellerInformation)
                            {
                                XmlNodeList bookData = book.ChildNodes;
                                foreach (XmlNode data in bookData)
                                {
                                    switch (data.Name)
                                    {
                                        case "SellerIdNum":
                                            Console.WriteLine($"销方ID: {data.InnerText.Trim()}");
                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "SellerIdNum", data.InnerText.Trim());
                                            break;
                                        case "SellerName":
                                            Console.WriteLine($"销方名称: {data.InnerText.Trim()}");
                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "SellerName", data.InnerText.Trim());
                                            break;
                                        case "SellerBankName":
                                            Console.WriteLine($"销方开户行: {data.InnerText.Trim()}");
                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "SellerBankName", data.InnerText.Trim());
                                            break;
                                        case "SellerBankAccNum":
                                            Console.WriteLine($"销方开户行号: {data.InnerText.Trim()}");
                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "SellerBankAccNum", data.InnerText.Trim());
                                            break;
                                    }
                                }
                            }

                            XmlNodeList booksBuyerInformation = xmlDoc.GetElementsByTagName("BuyerInformation");
                            foreach (XmlNode book in booksBuyerInformation)
                            {
                                XmlNodeList bookData = book.ChildNodes;
                                foreach (XmlNode data in bookData)
                                {
                                    switch (data.Name)
                                    {
                                        case "BuyerIdNum":
                                            Console.WriteLine($"买方ID: {data.InnerText.Trim()}");
                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "BuyerIdNum", data.InnerText.Trim());
                                            break;
                                        case "BuyerName":
                                            Console.WriteLine($"买方名称: {data.InnerText.Trim()}");
                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "BuyerName", data.InnerText.Trim());
                                            break;
                                    }
                                }
                            }

                            XmlNodeList booksIssuTaxSupervisionInfo = xmlDoc.GetElementsByTagName("TaxSupervisionInfo");
                            foreach (XmlNode book in booksIssuTaxSupervisionInfo)
                            {
                                XmlNodeList bookData = book.ChildNodes;
                                foreach (XmlNode data in bookData)
                                {
                                    switch (data.Name)
                                    {
                                        case "InvoiceNumber":
                                            Console.WriteLine($"票据号: {data.InnerText.Trim()}");
                                            break;
                                        case "IssueTime":
                                            Console.WriteLine($"开票时间: {data.InnerText.Trim()}");
                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "IssueTime", data.InnerText.Trim());
                                            break;
                                        case "TaxBureauCode":
                                            Console.WriteLine($"税务局ID: {data.InnerText.Trim()}");
                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "TaxBureauCode", data.InnerText.Trim());
                                            break;
                                        case "TaxBureauName":
                                            Console.WriteLine($"税务局名称: {data.InnerText.Trim()}");
                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "TaxBureauName", data.InnerText.Trim());
                                            break;
                                    }
                                }
                            }

                            XmlNodeList booksBasicInformation = xmlDoc.GetElementsByTagName("BasicInformation");
                            foreach (XmlNode book in booksBasicInformation)
                            {
                                XmlNodeList bookData = book.ChildNodes;
                                foreach (XmlNode data in bookData)
                                {
                                    switch (data.Name)
                                    {
                                        case "TotalAmWithoutTax":
                                            Console.WriteLine($"无税金额: {data.InnerText.Trim()}");
                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "TotalAmWithoutTax", data.InnerText.Trim());
                                            break;
                                        case "TotalTaxAm":
                                            Console.WriteLine($"税额: {data.InnerText.Trim()}");
                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "TotalTaxAm", data.InnerText.Trim());
                                            break;
                                        case "TotalTax-includedAmount":
                                            Console.WriteLine($"价税合计: {data.InnerText.Trim()}");
                                            EBillsMySqlTools.updateEBill(DBServerCFG, EIid, "TotalAmount", data.InnerText.Trim());
                                            break;
                                        case "TotalTax-includedAmountInChinese":
                                            Console.WriteLine($"价税合计中文: {data.InnerText.Trim()}");
                                            break;
                                    }
                                }
                            }
                            XmlNodeList booksIssuItemInformation = xmlDoc.GetElementsByTagName("IssuItemInformation");
                            int booksIssuItemIdx = 0;
                            foreach (XmlNode book in booksIssuItemInformation)
                            {
                                booksIssuItemIdx++;
                                XmlNodeList bookData = book.ChildNodes;
                                Console.WriteLine($"服务项目序号: {booksIssuItemIdx.ToString()}");

                                foreach (XmlNode data in bookData)
                                {
                                    switch (data.Name)
                                    {
                                        case "ItemName":
                                            Console.WriteLine($"项目名称: {data.InnerText.Trim()}");
                                            break;
                                        case "SpecMod":
                                            Console.WriteLine($"规格型号: {data.InnerText.Trim()}");
                                            break;
                                        case "MeaUnits":
                                            Console.WriteLine($"单位: {data.InnerText.Trim()}");
                                            break;
                                        case "Quantity":
                                            Console.WriteLine($"数量: {data.InnerText.Trim()}");
                                            break;
                                        case "UnPrice":
                                            Console.WriteLine($"无税单价: {data.InnerText.Trim()}");
                                            break;
                                        case "Amount":
                                            Console.WriteLine($"无税金额: {data.InnerText.Trim()}");
                                            break;
                                        case "TaxRate":
                                            Console.WriteLine($"税率: {data.InnerText.Trim()}");
                                            break;
                                        case "ComTaxAm":
                                            Console.WriteLine($"税额: {data.InnerText.Trim()}");
                                            break;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    iResult = false;
                }
            return iResult;
        }
    }
}